package com.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import android.content.Context;
import android.util.Log;

public class RUtil {

    public Context context;

    public RUtil(Context context) {
        this.context = context;
    }

    // 通过string-array name属性动态获取R.array.xxx的int值
    public int getRCode(String type, String name) {
        return context.getResources().getIdentifier(name, type, context.getPackageName());
    }

    /**
     * context.getResources().getIdentifier 无法获取到 styleable 的数据
     *
     * @param name
     * @return
     * @paramcontext
     */
    public int getStyleable(String type, String name) {
        return ((Integer) getResourceId(name, type)).intValue();
    }

    /**
     * 对于 context.getResources().
     * getIdentifier 无法获取的数据, 或者数组
     * 资源反射值
     *
     * @param name
     * @param type
     * @return
     * @paramcontext
     */
    private Object getResourceId(String name, String type) {

        String className = context.getPackageName() + ".R";

        try {

            Class<?> cls = Class.forName(className);

            for (Class<?> childClass : cls.getClasses()) {

                String simple = childClass.getSimpleName();

                if (simple.equals(type)) {

                    for (Field field : childClass.getFields()) {

                        String fieldName = field.getName();

                        if (fieldName.equals(name)) {
                            System.out.println(fieldName);
                            return field.get(null);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
